<template>
	<div>
		<!-- 面包屑导航 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>用户管理</el-breadcrumb-item>
			<el-breadcrumb-item>用户列表</el-breadcrumb-item>
		</el-breadcrumb>
		<!-- 卡片 -->
		<el-card class="box-card">
			<!-- 搜索与添加区域 -->
			<el-row :gutter="60">
				<el-col :span="7">
					<el-input placeholder="请输入内容" class="input-with-select" v-model="queryInfo.query" clearable @clear="getUser">
						<el-button slot="append" icon="el-icon-search" @click="getUser"></el-button>
					</el-input>
				</el-col>
				<el-col :span="4">
					<el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
				</el-col>
			</el-row>

			<!-- 用户列表区域 -->
			<el-table :data="userlist" border stripe>
				<el-table-column label="#" type="index"></el-table-column>
				<el-table-column label="姓名" prop="username"></el-table-column>
				<el-table-column label="邮箱" prop="email"></el-table-column>
				<el-table-column label="电话" prop="mobile"></el-table-column>
				<el-table-column label="角色" prop="role_name"></el-table-column>
				<el-table-column label="状态">
					<template v-slot="scope">
						<el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)">
						</el-switch>
					</template>
				</el-table-column>
				<el-table-column label="操作">
					<template v-slot="scope">
						<!-- 修改按钮 -->
						<el-button type="primary" icon="el-icon-edit" size="mini" @click="showXiu(scope.row.id)"></el-button>
						<!-- 删除按钮 -->
						<el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUser(scope
						.row.id)"> </el-button>
						<!-- 分配角色按钮 -->
						<el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
							<el-button type="warning" icon="el-icon-share" size="mini" @click="setRole(scope.row)"></el-button>
						</el-tooltip>
					</template>
				</el-table-column>
			</el-table>
			<!-- 分页区域 -->
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum"
			 :page-sizes="[1, 2, 3, 4]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
			</el-pagination>
		</el-card>
		<!-- 添加用户 -->
		<el-dialog title="提示" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
			<!-- 内容主题 -->
			<el-form :model="addForm" :rules="addFormrules" ref="addruleForm" label-width="100px">
				<el-form-item label="用户名称" prop="username">
					<el-input v-model="addForm.username"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input v-model="addForm.password"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input type="email" v-model="addForm.email"></el-input>
				</el-form-item>
				<el-form-item label="手机号" prop="mobile">
					<el-input v-model="addForm.mobile"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="addDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="addUser">确 定</el-button>
			</span>
		</el-dialog>

		<!-- 修改用户信息对话框 -->
		<el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editClose">
			<el-form :model="editFrom" :rules="ruleseditRules" ref="editFromRef" label-width="70px">
				<el-form-item label="用户名">
					<el-input v-model="editFrom.username" disabled></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="editFrom.email"></el-input>
				</el-form-item>
				<el-form-item label="手机" prop="mobile">
					<el-input v-model="editFrom.mobile"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="editDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="editUserInfo">确 定</el-button>
			</span>
		</el-dialog>
		<!-- 分配角色对话框 -->
		<el-dialog
		  title="分配角色"
		  :visible.sync="setRoledialogVisible"
		  width="50%"
		  @close="setRoledage">
		  <p>当前用户：{{userinfo.username}}</p>
			<p>当前角色：{{userinfo.role_name}}</p>
			<p>
				  <el-select v-model="setRoleDia" placeholder="请选择">
				    <el-option
				      v-for="item in roleList"
				      :key="item.id"
				      :label="item.roleName"
				      :value="item.id">
				    </el-option>
				  </el-select>
			</p>
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="setRoledialogVisible = false">取 消</el-button>
		    <el-button type="primary" @click="setRolesinfo">确 定</el-button>
		  </span>
		</el-dialog>
	</div>

</template>

<script>
	export default {
		data() {

			var checkEmail = (rule, value, cb) => {
				console.log(rule, value, cb)
				const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
				if (regEmail.test(value)) {
					return cb()
				}
				cb(new Error('输入正确邮箱'))
			}

			var checkMobile = (rule, value, cb) => {
				const regMobile = /^(1[3|5-9])\d{9}$/
				if (regMobile.test(value)) {
					return cb()
				}
				cb(new Error('输入正确手机号'))
			}

			return {
				//获取列表数据
				queryInfo: {
					query: '',
					// 当前页数
					pagenum: 1,
					// 当前页数每页显示数据
					pagesize: 2
				},
				userlist: [],
				total: 0,
				// 添加用户对话框的显示与隐藏
				addDialogVisible: false,
				// 控制修改用户对话框的显示与隐藏
				editDialogVisible: false,
				// 查询到的用户信息对象
				editFrom: {},
				// 分配角色对话框开关
				setRoledialogVisible: false,
				// 需要被分配角色的用户信息
				userinfo: {},
				// 所有角色列表数据
				roleList: [],
				// 已选中的角色ID
				setRoleDia: {},
				// 修改表单的验证规则
				ruleseditRules: {
					email: [{
							required: true,
							message: '请输入邮箱',
							trigger: 'blur'
						},
						{
							validator: checkEmail,
							trigger: 'blur'
						}
					],
					mobile: [{
							required: true,
							message: '请输入邮箱',
							trigger: 'blur'
						},
						{
							validator: checkMobile,
							trigger: 'blur'
						}
					]
				},


				// 用户表单
				addForm: {
					username: '',
					password: '',
					email: '',
					mobile: ''
				},
				// 添加表单的验证规则
				addFormrules: {
					username: [{
							required: true,
							message: '请输入用户名',
							trigger: 'blur'
						},
						{
							min: 3,
							mix: 10,
							message: '用户名长度在3~10位',
							trigger: 'blur'
						}
					],
					password: [{
							required: true,
							message: '请输入密码',
							trigger: 'blur'
						},
						{
							min: 3,
							mix: 10,
							message: '用户名长度在3~10位',
							trigger: 'blur'
						}
					],
					email: [{
							required: true,
							message: '请输入邮箱',
							trigger: 'blur'
						},
						{
							validator: checkEmail,
							trigger: 'blur'
						}
					],
					mobile: [{
							required: true,
							message: '请输入邮箱',
							trigger: 'blur'
						},
						{
							validator: checkMobile,
							trigger: 'blur'
						}
					]
				}
			}
		},
		created() {
			// this.$http.get('/users1', { 
			// 		params: this.queryInfo
			// 	})
			// 	.then(({
			// 		data: res
			// 	}) => {
			// 		this.userlist = res.data.users
			// 		this.total = res.data.total
			// 		// console.log(res)
			// 	})
			this.getUser()
		},
		methods: {
			async getUser() {
				const {
					data: res
				} = await this.$http.get('/users1', {
					params: this.queryInfo
				})
				this.userlist = res.data.users
				this.total = res.data.total
				console.log(res)
			},
			//监听handleSizeChange改变的事件 
			handleSizeChange(newSize) {
				this.queryInfo.pagesize = newSize
				this.getUser()
			},
			// 监听页码值改变
			handleCurrentChange(newPage) {
				this.queryInfo.pagenum = newPage
				this.getUser()
			},
			async userStateChanged(userinfo) {
				// console.log(userinfo)
				const {
					data: res
				} = await this.$http.get(`/users/${userinfo.id}/state/${userinfo.mg_state}`)
				console.log(res)
				if (res.meta.status !== 200) {
					userinfo.mg_state = !userinfo.mg_state
					return this.$message.error('失败')
				}
				this.$message.success('更新状态成功')
			},
			// 监听对话框关闭
			addDialogClosed() {
				this.$refs.addruleForm.resetFields()
			},
			// 点击按钮添加用户
			addUser() {
				this.$refs.addruleForm.validate(async valid => {
					if (!valid) return

					const {
						data: res
					} = await this.$http.post('/users', this.addForm)
					// if (res.meta.status !== 201) {
					// 	return this.$message.error('添加失败')
					// }
					this.$message.success('添加成功')
					this.addDialogVisible = false
					this.getUser()
				})
			},
			async showXiu(id) {
				const {
					data: res
				} = await this.$http.get('/users/' + id)
				if (res.meta.status !== 200) {
					return this.$message.error('查询失败')
				}
				this.editFrom = res.data
				this.editDialogVisible = true
				console.log(id)
			},
			// 重置修改用户对话框
			editClose() {
				this.$refs.editFromRef.resetFields()
			},

			// 修改用户信息提交
			editUserInfo() {
				this.$refs.editFromRef.validate(async valid => {
					if (!valid) return
					const {
						data: res
					} = await this.$http.put('/users/' + this.editFrom.id, {
						email: this.editFrom.email,
						mobile: this.editFrom.mobile
					})
					if (res.meta.status !== 200) {
						return this.$message.error('更新失败')
					}
					// 关闭对话框
					this.editDialogVisible = false
					// 刷新数据列表
					this.getUser()
					// 提示修改成功
					this.$message.success('成功')
				})
			},
			// 根据ID删除用户信息
			async removeUser(id) {
				console.log(id);
				const res = await this.$confirm('是否删除, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).catch(err => err)
					
				// 如果确认删除返回字符串confirm，如果取消返回cancel
				// console.log(res)
				if(res !== 'confirm') {
					return this.$message.info('已取消删除')
				}
			  
				const {data: res1} = await this.$http.delete('/usersremove/'+ id)
				if(res1.meta.status !== 200) {
					return this.$message.error('删除失败')
				}
				this.$message.success('删除成功')
				this.getUser()
				
			},
			async setRole(userinfo) {
				this.userinfo = userinfo
				const {data: res} = await this.$http.get('/roles')
				if(res.meta.status !== 200) {
					return $message.error('获取角色列表失败')
				}
				this.roleList = res.data
				this.setRoledialogVisible = true
			},
			
			// 点击按钮分配角色
			async setRolesinfo() {
				 if(!this.setRoleDia) {
				 	return this.$message.error('请选择要分配的角色')
				 }
				const { data : res } = await this.$http.put(`/users/${this.userinfo.id}/role`,{rid: this.setRoleDia})
				if(res.meta.status !== 200) {
					return this.$message.error('更新角色失败了')
				}
				this.$message.success('更新角色成功')
				this.getUser()
				this.setRoledialogVisible = false
				
			},
			setRoledage() {
				this.setRoledage = ''
				this.userinfo = {}
			}
			
		}
	}
</script>
`x
<style>
</style>
